package ru.ifmo.croak.impl.replication.team1.sync;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.impl.replication.team1.LocalContext;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;

public class SynchronizerTimer implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(SynchronizerTimer.class);

    private static final int DELAY_BETWEEN_SYNCHRONIZATION = 60000;
    private final SynchronizerManager synchronizer;
    private final LocalContext localContext;
    private static final int SO_TIMEOUT = 10000;

    public SynchronizerTimer(SynchronizerManager synchronizer, LocalContext localContext) {
        this.synchronizer = synchronizer;
        this.localContext = localContext;
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(DELAY_BETWEEN_SYNCHRONIZATION);
                SocketAddress socketAddress = localContext.getRandomAliveHost();
                if (socketAddress == null) {
                    continue;
                }
                Socket socket = new Socket();
                try {
                    socket.setSoTimeout(SO_TIMEOUT);
                    socket.connect(socketAddress);
                } catch (IOException e) {
                    localContext.removeAliveHost(socketAddress);
                }
                synchronizer.synchronizeTo(socket);
            }

        } catch (InterruptedException e) {
            log.info("Thread was interrupted", e);
            Thread.currentThread().interrupt();
        }

    }
}
